﻿package src.sound {
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class SoundPlayer extends EventDispatcher{
		private var sound:Sound;
		private var repeat:Boolean;
		private var transform:SoundTransform;
		private var channel:SoundChannel;
		
		public function SoundPlayer(sound:Sound) {
			this.sound = sound;
			transform = new SoundTransform();
			channel = new SoundChannel();
			
			repeat = false;
		}
		
		public function setRepeat(value:Boolean):void {
			this.repeat = value;
		}
		
		public function isRepetable():Boolean {
			return repeat;
		}
		
		public function setVolume(value:Number):void {
			transform.volume = value;
			channel.soundTransform = transform;
		}
		
		public function play():void {
			channel = sound.play(0, 0, transform);
    			channel.addEventListener(Event.SOUND_COMPLETE, onComplete);
		}
		
		public function stop():void {
			channel.stop();
		}

		private function onComplete(event:Event):void {
    		SoundChannel(event.target).removeEventListener(event.type, onComplete);
    		dispatchEvent(new Event(Event.SOUND_COMPLETE));
		}
	}
}
